package com.ygqh.baby.service.impl;

import com.ygqh.baby.ao.DataStatus;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.ao.UserType;
import com.ygqh.baby.mapper.YgChannelCategoryMapper;
import com.ygqh.baby.mapper.YgChannelMapper;
import com.ygqh.baby.model.YgChannelBalance;
import com.ygqh.baby.po.YgChannel;
import com.ygqh.baby.po.YgChannelCategory;
import com.ygqh.baby.po.YgChannelCategoryExample;
import com.ygqh.baby.po.YgChannelExample;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgUserBalance;
import com.ygqh.baby.po.YgUserOpen;
import com.ygqh.baby.service.SmsService;
import com.ygqh.baby.service.YgChannelService;
import com.ygqh.baby.service.YgMobileService;
import com.ygqh.baby.service.YgUserBalanceService;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.utils.YgStringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class YgChannelServiceImpl implements YgChannelService {

	private Logger logger = Logger.getLogger(YgChannelService.class);
	@Autowired
	private YgChannelMapper ygChannelMapper;
	@Autowired
	private YgChannelCategoryMapper ygChannelCategoryMapper;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private YgMobileService ygMobileService;
	@Autowired
	private YgUserBalanceService userBalanceService;
	@Autowired
	private SmsService smsService;
	@Value("${default.head.url}")
	private String defaultHeadUrl;
	@Value("${promotion.link}")
	protected String promotionLink;
	@Value("${channel.link}")
	protected String channelLink;

	@Override
	public List<YgChannel> find() {
		YgChannelExample example = new YgChannelExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygChannelMapper.selectByExample(example);
	}

	@Override
	public int findCount() {
		YgChannelExample example = new YgChannelExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygChannelMapper.countByExample(example);
	}

	@Override
	public YgChannel findById(Long id) {
		return ygChannelMapper.selectByPrimaryKey(id);
	}

	@Override
	public int save(YgChannel ygChannel) {

		String username = "";
		// 主用户
		if (ygChannel.getParentId() == null) {
			// 主用户
			username = ygChannel.getSourceCode();
		} else {
			// 子用户
			// 获取主账户下的子账号个数
			int count = 0;
			List<YgChannel> list = this.findByParentId(ygChannel.getParentId());
			if (list != null) {
				count = list.size() - 1;
				count++;
			}
			if (count < 10) {
				username = ygChannel.getSourceCode() + "000" + count;
			} else if (count > 10 && count < 100) {
				username = ygChannel.getSourceCode() + "00" + count;
			} else if (count > 100 && count < 1000) {
				username = ygChannel.getSourceCode() + "0" + count;
			} else {
				username = ygChannel.getSourceCode() + count;
			}
			ygChannel.setCreateTime(new Date());
			YgChannel record = new YgChannel();
			record.setId(ygChannel.getParentId());
			record.setSubAmount((long) count);
			ygChannelMapper.updateByPrimaryKeySelective(record);
		}
		ygChannel.setSourceCode(username);
		int row = ygChannelMapper.insertSelective(ygChannel);

		// 创建用户
		YgUser ygUser = new YgUser();
		ygUser.setUserName(username);
		String pwd = YgStringUtils.getRandomLong(6);
		ygUser.setPassword(pwd);
		ygUser.setTelPhone(ygChannel.getTelPhone());
		ygUser.setSourceCode(username);
		ygUser.setBabyBirthday(null);
		ygUser.setBabyGender(null);
		ygUser.setGender(null);
		ygUser.setHeadImageUrl(defaultHeadUrl);
		ygUser.setNickName(ygChannel.getLinkMan());
		ygUser.setCreateTime(new Date());
		ygUser.setIsSeller(true);
		ygUser.setUserType(UserType.Channel);
		ygUser.setForeverRate(ygChannel.getForeverRate());
		ygUser.setShareRate(ygChannel.getCommissionRate());
		ygUserService.save(ygUser);

		YgUserBalance userBalance = new YgUserBalance();
		userBalance.setBalancePrice(new BigDecimal(0));
		userBalance.setCreateTime(new Date());
		userBalance.setFreezePrice(new BigDecimal(0));
		userBalance.setPreincomePrice(new BigDecimal(0));
		userBalance.setUserId(ygUser.getId());
		userBalance.setWithdrawPrice(new BigDecimal(0));
		userBalanceService.save(userBalance);

		// 用户创建成功，发送短信
		String content = "您已成为【" + ygChannel.getShortName() + "】的推广员，网址:" + channelLink + "，用户名:" + ygUser.getUserName() + "，密码:" + pwd + "。";
		System.out.println("====" + content);
		smsService.sendSms(ygUser.getTelPhone(), content);

		return row;
	}

	@Override
	public List<YgChannel> findByParentId(Long parentId) {
		return ygChannelMapper.selectByParentId(parentId);

	}

	@Override
	public List<String> findSourceCodeWithParent(Long userId) {
		return ygChannelMapper.findSourceCodeWithParent(userId);
	}

	@Override
	public int update(YgChannel ygChannel) {
		List<YgChannel> channels =  this.findByParentId(ygChannel.getId());
		channels.forEach(c->{
			YgUser user = new YgUser();
			user.setSourceCode(c.getSourceCode());
			user.setUserName(c.getSourceCode());
			user.setNickName(c.getLinkMan());
			user.setForeverRate(ygChannel.getForeverRate());
			user.setShareRate(ygChannel.getCommissionRate());
			c.setGreetings(ygChannel.getGreetings());
			c.setForeverRate(ygChannel.getForeverRate());
			c.setCommissionRate(ygChannel.getCommissionRate());
			ygChannelMapper.updateByPrimaryKeySelective(c);
			ygUserService.updateUserBySourceCode(user);
		});

		return 1;
	}

	@Override
	public int updateStatus(YgChannel ygChannel) {
		ygChannelMapper.updateByPrimaryKeySelective(ygChannel);

		return 1;
	}

	@Override
	public ResultSet<YgChannel> search(QueryInfo queryInfo, Long categoryId, String sourceCode, String q) {
		List<YgChannel> list = ygChannelMapper.selectSuper(queryInfo, categoryId, sourceCode, q);
		int count = ygChannelMapper.countSuper(categoryId, sourceCode, q);
		ResultSet<YgChannel> resultSet = new ResultSet<YgChannel>(count, list);
		return resultSet;
	}

	@Override
	public int deleteSoft(Long[] ids) {
		Assert.notEmpty(ids);
		YgChannelExample example = new YgChannelExample();
		example.createCriteria().andIdIn(Arrays.asList(ids));
		YgChannel record = new YgChannel();
		record.setStatus(DataStatus.Delete);

		return ygChannelMapper.updateByExampleSelective(record, example);
	}

	@Override
	public int deleteSoft(Long id) {
		return this.deleteSoft(new Long[] { id });
	}

	@Override
	public int saveOrUpdate(YgChannel ygChannel) {
		int r = 0;
		if (ygChannel.getId() != null) {
			r = this.update(ygChannel);
		} else {
			r = this.save(ygChannel);
		}
		return r;
	}

	@Override
	public List<YgChannelCategory> findAllChannelCategory() {
		YgChannelCategoryExample example = new YgChannelCategoryExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygChannelCategoryMapper.selectByExample(example);
	}

	@Override
	public Boolean isExist(Long channelId, String sourceCode) {
		YgChannelExample example = new YgChannelExample();
		YgChannelExample.Criteria criteria = example.createCriteria();
		criteria.andSourceCodeEqualTo(sourceCode);
		if (channelId != null) {
			criteria.andIdNotEqualTo(channelId);
		}
		List<YgChannel> list = ygChannelMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			return true;
		}
		return false;
	}

	@Override
	public int saveChannelCategory(YgChannelCategory category) {
		return ygChannelCategoryMapper.insertSelective(category);
	}

	@Override
	public ResultSet<YgChannelCategory> searchChannelCategory(QueryInfo queryInfo, String q) {

		List<YgChannelCategory> result = ygChannelCategoryMapper.selectSuper(queryInfo, q);
		int row = ygChannelCategoryMapper.countSuper(q);
		return new ResultSet<YgChannelCategory>(row, result);
	}

	@Override
	public int updateChannelCategory(YgChannelCategory category) {
		Assert.notNull(category.getId());
		return ygChannelCategoryMapper.updateByPrimaryKeySelective(category);
	}

	@Override
	public Boolean isExistCategory(Long categoryId, String categoryName) {
		YgChannelCategoryExample example = new YgChannelCategoryExample();
		YgChannelCategoryExample.Criteria criteria = example.createCriteria();

		criteria.andStatusEqualTo(DataStatus.Valid.name()).andCategoryNameEqualTo(categoryName);
		if (categoryId != null) {
			criteria.andIdNotEqualTo(categoryId);
		}
		int count = ygChannelCategoryMapper.countByExample(example);
		return count > 0 ? true : false;
	}

	@Override
	public int deleteSoftChannelCategory(Long[] categoryIds) {
		Assert.notEmpty(categoryIds);
		YgChannelCategoryExample example = new YgChannelCategoryExample();
		example.createCriteria().andIdIn(Arrays.asList(categoryIds));
		YgChannelCategory record = new YgChannelCategory();
		record.setStatus(DataStatus.Delete);
		return ygChannelCategoryMapper.updateByExample(record, example);
	}

	@Override
	public YgChannel findByCode(String sourceCode) {
		YgChannelExample example = new YgChannelExample();
		YgChannelExample.Criteria criteria = example.createCriteria();
		criteria.andSourceCodeEqualTo(sourceCode).andStatusEqualTo(DataStatus.Valid.name());
		List<YgChannel> list = ygChannelMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<YgChannel> findChannelDetailByParent(Long parentId) {
		Assert.notNull(parentId);
		return ygChannelMapper.selectChannelDetailByParent(parentId);
	}

	@Override
	public List<YgUserOpen> findChannelScanAmount(Date startDate, Date endDate) {
		return ygChannelMapper.findChannelScanAmount(startDate, endDate);
	}

	@Override
	public List<YgUser> findChannelRegAmount(Date startDate, Date endDate) {
		return ygChannelMapper.findChannelRegAmount(startDate, endDate);
	}

	@Override
	public int updateScanAmountBatch(List<YgChannel> channelList) {
		return ygChannelMapper.updateScanAmountBatch(channelList);
	}

	@Override
	public List<YgChannel> findAllParentChannel() {
		YgChannelExample example = new YgChannelExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andParentIdEqualTo(0l);
		return ygChannelMapper.selectByExample(example);
	}

	@Override
	public void executeChannelScanAndRegTask(Date startDate, Date endDate) {
		ygChannelMapper.executeChannelScanAndRegTask(startDate, endDate);
	}

	@Override
	public List<YgChannelBalance> findAllChildChannel() {
		return ygChannelMapper.findAllChildChannel();
	}

	@Override
	public YgChannelBalance findChannelBalanceByParentId(Long parentId) {
		return ygChannelMapper.findChannelBalanceByParentId(parentId);
	}

}
